﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using LikeTryCore;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Net;
using Contract;

namespace LikeTryServices
{
    public partial class Service1 : ServiceBase
    {
        private Thread t;
        private Thread[] TaskThread;
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            try
            {
                List<LikeAccount> accountObj = null;
                try
                {
                    ////No data in server cache.
                    accountObj = LikeTry.GetAccountList();
                }
                catch (Exception exp)
                {
                    accountObj = new List<LikeAccount>();
                    EventLog.WriteEntry(exp.Message);
                }

                ////Can read logon cookie form cache file.
                if (accountObj != null && accountObj.Count > 0)
                {
                    ////Create new thread to keep user online for each account.
                    t = new Thread(new LikeTryOper(accountObj).KeepOnline);
                    t.Priority = ThreadPriority.Highest;
                    t.IsBackground = true;
                    t.Name = "keeponline";
                    t.Start();

                    TaskThread = new Thread[accountObj.Count];
                    for (int i = 0; i < accountObj.Count; i++)
                    {
                        LikeTry liketry = new LikeTry(accountObj[i].Cookies);
                        TaskThread[i] = new Thread(liketry.Execute);
                        TaskThread[i].IsBackground = true;
                        TaskThread[i].Name = accountObj[i].Name + accountObj[i].Id.ToString();
                        TaskThread[i].Start();
                    }
                }
            }
            catch(Exception eeepo)
            {
                Trace.Write(eeepo);
                throw;
            }
        }

        protected override void OnStop()
        {
            if (t != null)
            {
                try
                {
                    t.Abort();
                }
                catch (Exception)
                {
 
                }
            }

            if (TaskThread != null)
            {
                foreach (var item in TaskThread)
                {
                    item.Abort();
                }
            }
        }
    }
}
